package com.lagou.consumer;

import com.lagou.dto.UserBuyProductMsg;
import com.lagou.entity.COrder;
import com.lagou.repository.COrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author mcl
 * @date 2021/10/14 02:52
 * @description
 */

@Slf4j
@Component
@RocketMQMessageListener(topic = "order_create", consumerGroup = "order_create_consumer")
public class OrderCreateConsumer implements RocketMQListener<UserBuyProductMsg> {
    @Autowired
    private COrderRepository cOrderRepository;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(UserBuyProductMsg message) {
        // 创建订单 注意密等
        COrder order;

        List<COrder> bySql = cOrderRepository.findBySql(message.getUserId(), message.getProductId());
        if (bySql.size() > 0) {
            order = bySql.get(0);
        } else {
            order = new COrder();
            order.setUserId(message.getUserId());
            order.setProductId(message.getProductId());
            order.setStatus("Paying");
            order.setCreateTime(new Date());
            cOrderRepository.save(order);
        }

        // 支付超时消息
        rocketMQTemplate.syncSend("orer_timeout", MessageBuilder.withPayload(order).build(),10L,4);
    }
}
